define(['jquery','treeView'],function($){
    'use strict';
	angular.module('backcenter.sysInfoTree', ['app.treeView'])
    .controller('sysInfoTreeCtrl'
		,['$rootScope', '$scope', '$uibModal', 'BizData', '$state', '$ocLazyLoad'
                                   ,f])
      	 function f($rootScope,$scope, $uibModal ,BizData,$state, $ocLazyLoad
   	          ) {
   		$scope.headerText = '----------我是系统客户区sysInfoTreeCtrl控制器！id为-->'+$scope.$id+'开始----------';
   		$scope.footerText = '----------我是系统客户区sysInfoTreeCtrl控制器！id为-->'+$scope.$id+'结束----------';

   		var Model = this;
   		
   		var common = require('common');
   		
   		$scope.appId = 'appId';
   		

   		/**
   		name:bizData#onBeforeDelete
   		description: <b>[回调型事件]</b>业务数据删除前
   		@param {object} event 它的结构如下:<br/>
   		{
   			"source":组件的js对象
   			,"cancel":可修改	，设置为true后中断当前delete动作
   			,"deleteIDList":删除的行Id数组
   		}
   		*/
   		Model.dataSysInfoBeforeDelete = function(event) {
   			
   		}
   		/**
   		name:bizData#onAfterDelete
   		description: <b>[回调型事件]</b>业务数据删除后
   		@param {object} event 
   		<br/><b>结构如下：</b>
   		<xmp> 
   		{
   			"source" : 组件的js对象,
   			"deleteIDList" : 删除的行Id数组
   		}
   		</xmp>	
   		*/
   		Model.dataSysInfoAfterDelete = function(event) {
//                               			alert('删除之后！')
   		}

   		
   		
   		/**
   		name:bizData#onIndexChanging
   		description: <b>[回调型事件]</b>行记录变化中
   		@param {object} event 
   		<br/><b>结构如下：</b>
   		<xmp> 
   		{
   			"source" : 组件的js对象,
   			"rowID" : 行Id,
   			"rowIndex" : 行索引,
   			"originalRowID" : 原行Id,
   			"originalRowIndex" : 原行索引
   		}
   		</xmp>	
   		*/
   		Model.dataSysInfoIndexChanging = function(event){
   			
   		};
   		
   		
   		/**
   		name:bizData#onIndexChanged
   		description: <b>[回调型事件]</b>行记录变化
   		@param {object} event 
   		<br/><b>结构如下：</b>
   		<xmp> 
   		{
   		"source" : 组件的js对象,
   		"rowID" : 行Id,
   		"rowIndex" : 行索引
   		}
   		</xmp>	
   		*/
   		Model.dataSysInfoIndexChanged = function(event) {
   			
   		}
   		
   		/**
   		name:bizData#onDataChanged
   		description: <b>[回调型事件]</b>数据发生变化（包括新增、刷新、删除、修改引起的变化），感知从data的变化
   		@param {object} event 
   		<br/><b>结构如下：</b>
   		<xmp> 
   		{
   		"source" : 组件的js对象,
   		"changedSource" ：触发变化的组件的js对象，当从data触发时返回从data对象,
   		"selfChanged" : 是否自身变化，false：从data触发的变化,
   		"type" : 触发变化的类型，包括：new、delete、refresh、valueChanged、clear，其他参数根据触发类型不同给出不同参数，参考onAfterNew等事件参数
   		}
   		</xmp>	
   		*/
   		Model.dataSysInfoDataChanged = function(event) {
   			
   		}
   		
   		/**
   		name:bizData#onValueChanged
   		description: <b>[回调型事件]</b>数据变化
   		@param {object} event 
   		<br/><b>结构如下：</b>
   		<xmp> 
   		{
   		"source" : 组件的js对象,
   		"column" : 关系,
   		"rowIndex" : 行索引,
   		"value" : 新值,
   		"originalValue" : 旧值
   		}
   		</xmp>	
   		*/
   		//输入值变化，监视input的输入，ng-change
   		Model.dataSysInfoValueChanged = function(event) {
   			if(event.column=='systemCode'){
   				//整合自身全路径编码
   				var rowID = event.source.getID(event.rowIndex);
   				var fParent = event.source.getValue('fParent',rowID);
   				var systemCode = event.value;
   				var systemFullCode = '';
   				if(fParent==null || fParent==''){
   					systemFullCode = systemFullCode + '/' + systemCode;
   				}else{
   					systemFullCode = event.source.getValue('systemFullCode',fParent) + '/' + systemCode;
   				}
   				event.source.setValue('systemFullCode',systemFullCode,rowID);
   			}
   			if(event.column=='systemFullCode'){
   				//修改子节点的全路径编码
   				var rowID = event.source.getID(event.rowIndex);
   				var ids = $scope.dataSysInfo.getChildsIDs(rowID);
   				for(var i=0;i<ids.length;i++){
   					var systemFullCode = event.value + '/' + event.source.getValue('systemCode',ids[i]);
   					event.source.setValue('systemFullCode',systemFullCode,ids[i]);
   				}
   			}
   			if(event.column=='systemName'){
   				//整合自身全路径名称
   				var rowID = event.source.getID(event.rowIndex);
   				var fParent = event.source.getValue('fParent',rowID);
   				var systemName = event.value;
   				var systemFullName = '';
   				if(fParent==null || fParent==''){
   					systemFullName = systemFullName + '/' + systemName;
   				}else{
   					systemFullName = event.source.getValue('systemFullName',fParent) + '/' + systemName;
   				}
   				event.source.setValue('systemFullName',systemFullName,rowID);
   			}
   			if(event.column=='systemFullName'){
   				//修改子节点的全路径名称
   				var rowID = event.source.getID(event.rowIndex);
   				var ids = $scope.dataSysInfo.getChildsIDs(rowID);
   				for(var i=0;i<ids.length;i++){
   					var systemFullName = event.value + '/' + event.source.getValue('systemName',ids[i]);
   					event.source.setValue('systemFullName',systemFullName,ids[i]);
   				}
   			}

   			
   		}
   		


   		/**
   		name:bizData#onBeforeNew
   		description: <b>[回调型事件]</b>业务数据新增前
   		@param {object} event 它的结构如下:<br/>{"source":组件的js对象,"cancel":可修改，设置为true后中断当前new动作}
   		*/
   		Model.dataSysInfoBeforeNew = function(event) {

   		};
   		
   		
   		/**
   		* name:bizData#onAfterNew description: <b>[回调型事件]</b>业务数据新增后
   		* 
   		* @param event
   		*            它的结构如下:<br/>{"source":组件的js对象,"id":新增的行Id}
   		*/
   		Model.dataSysInfoAfterNew = function(event){
   			
   			//整合自身全路径编码
   			var fID = event.id;
   			var fParent = event.source.getValue('fParent',fID);
   			var systemKind = event.source.getValue('systemKind',fID);
   			var systemFullID = '';
   			if(fParent==null || fParent==''){
   				systemFullID = '/' + fID + '.' + systemKind;
   			}else{
   				systemFullID = event.source.getValue('systemFullID',fParent) + '/' + fID + '.' + systemKind;
   				//展开父节点
   				$scope.dataSysInfo.expandRow(fParent);
   			}
   			event.source.setValue('systemFullID',systemFullID,fID);
   			event.source.setValue('appId',$scope.appId,fID);
   			event.source.setValue('appName',$scope.appName,fID);
   			event.source.setValue('sDisplay','Y');
   			

   		}
   		
   		
   		
   		
   		///////////////////按钮组开始///////////////////////////////////////////////////
   		//新建（跟）
   		Model.addRoot = function(){
   			if($scope.appId==''){
   				alert('请选择服务商提供的软件系统');
   				return;
   			}

   		//	if($scope.dataSysInfo.getTotal()<=0){
   		//		$scope.dataSysInfo.loadData('');
   		//	}
   			//树形专用
   			var nodeKind = 'nkLeaf';
   			var fParent = null;
   			var systemFullID = null;
   			var nodeLevel = 1;
   			var sortNo = null;
   			var systemKind = 'app';
   			
   			fParent = null;
   			systemFullID = null;
   			nodeLevel = 1;
   			var rootCount = $scope.dataSysInfo.getRoots().length;
   			sortNo = '/' + common.preZeroFill(rootCount + 1,3);
   			
   			var options = {
   					index : $scope.dataSysInfo.rows.length,
   					defaultValues : [
   					                 {
   						            	 status:'close'
   						            	 
   					                	 ,fParent:fParent
   					                	 ,nodeKind:nodeKind
   					                	 ,nodeLevel:nodeLevel
   					                	 ,sortNo:sortNo
   					                	 
   					                	 ,systemKind:systemKind
   						            	 ,itemPrice:0
   						            	 
   						            	 ,version:0
   					                	 }
//                               						                 ,{sName:'a2',sCode:'b2'}
   					                 ]
   			};    

   			var ids = $scope.dataSysInfo.newData(options);
   			
   		}
   		//新建子节点
   		Model.addChild = function(systemKind){
   			if($scope.appId==''){
   				alert('请选择服务商提供的软件系统');
   				return;
   			}

   			//树形专用
   			var nodeKind = 'nkLeaf';
   			var fParent = null;
   			var systemFullID = null;
   			var nodeLevel = 1;
   			var sortNo = null;
   			
   			if($scope.dataSysInfo.currentIndex== -1){return;}
   			fParent = $scope.dataSysInfo.currentID;
   			var parentIndex = $scope.dataSysInfo.getIndex(fParent);
   			systemFullID = $scope.dataSysInfo.rows[$scope.dataSysInfo.currentIndex].systemFullID.value;
   			nodeLevel = $scope.dataSysInfo.rows[$scope.dataSysInfo.currentIndex].nodeLevel.value + 1;
   			var childCount = $scope.dataSysInfo.getChilds(fParent).length;
   			
   			sortNo =$scope.dataSysInfo.rows[$scope.dataSysInfo.currentIndex].sortNo.value + '/' + common.preZeroFill(childCount + 1,3);
   			//设置父节点的节点类型为（非叶子）转到BizData中处理
//                               			$scope.dataSysInfo.rows[$scope.dataSysInfo.currentIndex].nodeKind.value = null;			

   			var childrenCount = $scope.dataSysInfo.getChildren(fParent).length;
   			var options = {
   					index : parentIndex + childrenCount + 1,
   					defaultValues : [
   					                 {
   						            	 status:'close'
   						            	 
   					                	 ,fParent:fParent
   					                	 ,nodeKind:nodeKind
   					                	 ,nodeLevel:nodeLevel
   					                	 ,sortNo:sortNo
   					                	 
   					                	 ,systemKind:systemKind
   						            	 ,itemPrice:0
   						            	 
   						            	 ,version:0
   					                	 }
//                               						                 ,{sName:'a2',sCode:'b2'}
   					                 ]
   			};    

   			var ids = $scope.dataSysInfo.newData(options);
   		}
   		
   		/*
		//新建兄弟节点
		Model.addBrother = function(){
			//树形专用
			var nodeKind = 'nkLeaf';
			var fParent = null;
			var systemFullID = null;
			var nodeLevel = 1;
			var sortNo = null;
			
			if($scope.dataSysInfo.currentIndex== -1){return;}
			fParent =  $scope.dataSysInfo.rows[$scope.dataSysInfo.currentIndex].fParent.value;
			if(fParent==null || fParent==''){return;}
			var parentIndex = $scope.dataSysInfo.getIndex(fParent);
			systemFullID = $scope.dataSysInfo.rows[parentIndex].systemFullID.value;
			nodeLevel = $scope.dataSysInfo.rows[$scope.dataSysInfo.currentIndex].nodeLevel.value;
			var childCount = $scope.dataSysInfo.getChilds(fParent).length;
			sortNo =$scope.dataSysInfo.rows[parentIndex].sortNo.value + '/' + common.preZeroFill(childCount + 1,3);
			
			//$scope.dataSysInfo.rows[$scope.dataSysInfo.currentIndex].nodeKind.value = null;			
			
			var childrenCount = $scope.dataSysInfo.getChildren(fParent).length;
			var options = {
					index : parentIndex + childrenCount + 1,
					defaultValues : [
					                 {
						            	 status:'open'
						            	 
					                	 ,fParent:fParent
					                	 ,nodeKind:nodeKind
					                	 ,nodeLevel:nodeLevel
					                	 ,sortNo:sortNo
						            	 
						            	 ,version:0
					                	 }
					                 //,{sName:'a2',sCode:'b2'}
					                 ]
			};    

			var ids = $scope.dataSysInfo.newData(options);
		}
		*/
   		
   		//修改
   		Model.edit = function(){
   			$scope.dataSysInfo.editData();
   		}
   		
   		//保存
   		Model.save = function() {
   			$scope.dataSysInfo.saveData();
   		}
   		
   		//取消保存
   		Model.saveCancel = function() {
   			/*
   			if($scope.dataSysInfo.recordState == 'new'){
   				$scope.dataSysInfo.loadPageData();
   			}else{
   				$scope.dataSysInfo.refreshPageData();
   			}
   			*/
//   			$scope.dataSysInfo.refreshData();
			$scope.dataSysInfo.editCancel();
   		}
   		
   		//直接删除
   		Model.remove = function() {
   			 if($scope.dataSysInfo.directDeleteMode){
   				 if($scope.dataSysInfo.deleteData($scope.dataSysInfo.getCurrentID())==0){
   					 $scope.dataSysInfo.refreshData();
   				 }
   			 }else{
   				 if($scope.dataSysInfo.removeData($scope.dataSysInfo.getCurrentID())==0){
   				 }
   				 $scope.dataSysInfo.editData();
   			 }

   		};
   		
   		//刷新
   		Model.refresh = function() {
   			if($scope.appId==''){
   				alert('请选择服务商提供的软件系统');
   				return;
   			}
   	   		$scope.dataSysInfo.filter = "SysInfo.appId='"+$scope.appId+"'";

   			$scope.dataSysInfo.refreshData();
   		}
		
		//排序
		Model.sort = function(fParent) {
   			if($scope.appId==''){
   				alert('请选择服务商提供的软件系统');
   				return;
   			}
			var parentID = null;
			if(fParent!='root'){
				parentID = $scope.dataSysInfo.getCurrentID();
			}

			var options = {};
			
			options.recordState = 'none';
			options.id = '';
			options.parentID = parentID;
			options.appId = $scope.appId;

	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: '',
	            templateUrl: $rootScope.getProjectName() + '/backcenter/sysInfo/sortView',  
	            controller: 'sysInfoSortCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '选择'; }
                    ,loadCtrl : $ocLazyLoad.load('js/sysInfo/sort')
		        }
	        });  
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
				
				//装配参数
				var data = new Object();
				data.parentID = parentID;
				data.ids = returnData;
				
				var response = $.ajax({
		            type: "POST",
		            async : false,
		            url: $rootScope.getProjectName() + "/backcenter/sysInfo/sort",
		            data: JSON.stringify(data),// "{}",
		            contentType: "application/json; charset=utf-8",
		            dataType: "json",
//		            processData: false,
		            success: function (data) {
		                // Play with returned data in JSON format
		            },
		            error: function (msg) {
//		                alert(msg.responseText);
		            }
		        });

				if (response.readyState == 4 && response.status == 200) {
    				$scope.dataSysInfo.refreshPageData();
    				if(parentID!=null){
    					$scope.dataSysInfo.expandRow(parentID);
    				}
    				return 0;
    			}else{
    				alert('操作失败！')
    				return -1;
    			}
				
				

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
		};
		
		//移动
		Model.move = function() {
   			if($scope.appId==''){
   				alert('请选择服务商提供的软件系统');
   				return;
   			}
			var options = {};
			options.appId = $scope.appId;

	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: '',
	            templateUrl: $rootScope.getProjectName() + '/backcenter/sysInfo/moveView',  
	            controller: 'sysInfoMoveCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '选择'; }
                    ,loadCtrl : $ocLazyLoad.load('js/sysInfo/move')
		        }
	        });  

	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
				console.log('returnData-->',returnData);
				
				//新父节点ID
				var newParentID = null;
				if(returnData!=null){
					//移动到顶层
					newParentID = returnData[0].fID;
				}
				console.log('newParentID-->',newParentID);
				
				var dataMaster = $scope.dataSysInfo;//Model.dataMaster;
				var rowID = dataMaster.getCurrentID();
				var oldParentID = dataMaster.getValue('fParent',rowID);
				//前后父节点不能相同
				if(newParentID==oldParentID){
					return;
				}
				
				//只能是页面级移动
				var oldSystemKind = dataMaster.getValue('systemKind',oldParentID);
				var newSystemKind = dataMaster.getValue('systemKind',newParentID);
				if(oldSystemKind!='fun' || newSystemKind!='fun' ){
					alert('只能在功能之间进行页面移动！');
					return;
				}
				
				//装配参数
				
				var data = new Object();
				data.rowID = rowID;
				data.oldParentID = oldParentID;
				data.newParentID = newParentID;
				data.appId = $scope.appId;

				var response = $.ajax({
		            type: "POST",
		            async : false,
		            url: $rootScope.getProjectName() + "/backcenter/sysInfo/move",
		            data: JSON.stringify(data),// "{}",
		            contentType: "application/json; charset=utf-8",
		            dataType: "json",
//		            processData: false,
		            success: function (data) {
		                // Play with returned data in JSON format
		            },
		            error: function (msg) {
//		                alert(msg.responseText);
		            }
		        });

				if (response.readyState == 4 && response.status == 200) {
    				dataMaster.refreshPageData();
    				var index = dataMaster.getIndex(rowID);
    				dataMaster.setCurrentIndex(index);
    				if(newParentID!=null){
    					dataMaster.expandRow(newParentID);
    				}
    				return 0;
    			}else{
    				alert('操作失败！')
    				return -1;
    			}
				
				

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
	        
		};
		
		

   		///////////////////按钮组结束///////////////////////////////////////////////////

   		/*
   		//监视器回调函数
   		Model.rowsWatcherFn = function() {
   			return $scope.$watch('dataSysInfo.rows',$scope.dataSysInfo.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
   		}
   		*/

   		///////////对象封装测试/////////////////////////
   		
   		var options = {};
		options.container = Model;
		options.concept = 'SysInfo';
		options.name = 'dataSysInfo';
		options.url = $rootScope.path;
		options.httpUrl = $rootScope.getServiceName();
		options.creater = '/backcenter/sysInfo/tree/create';
   		options.reader = '/backcenter/sysInfo/tree/query';
   		options.writer = '/backcenter/sysInfo/tree/save';
   		options.deleter = '/backcenter/sysInfo/tree/delete';
   		options.idColumnDefine = "fID";
   		options.idColumnName = "fID";
   		options.defCols = {fID:{name:"fID",type:"String",label:""},sDisplay:{name:"sDisplay",type:"String",label:""},appId:{name:"appId",type:"String",label:""},appName:{name:"appName",type:"String",label:""},systemCode:{name:"systemCode",type:"String",label:""},systemName:{name:"systemName",type:"String",label:""},systemFullID:{name:"systemFullID",type:"String",label:""},systemFullCode:{name:"systemFullCode",type:"String",label:""},systemFullName:{name:"systemFullName",type:"String",label:""},systemKind:{name:"systemKind",type:"String",label:""},systemDescribe:{name:"systemDescribe",type:"String",label:""},itemPrice:{name:"itemPrice",type:"Decimal",label:""},absoluteUrl:{name:"absoluteUrl",type:"String",label:""},nodeLevel:{name:"nodeLevel",type:"Integer",label:""},nodeKind:{name:"nodeKind",type:"String",label:""},sortNo:{name:"sortNo",type:"String",label:""},fParent:{name:"fParent",type:"String",label:""},status:{name:"status",type:"String",label:""},version:{name:"version",type:"Integer",label:""}};
   		options.isTree = true;
   		options.parentRelation = 'fParent';
   		options.nodeKindRelation = 'nodeKind';
   		options.nodeLevelRelation = 'nodeLevel';
   		options.nodeSortRelation = "sortNo";
//   	options.rootFilter = 'SysInfo.fParent is null';
   		options.pathRelation = 'systemFullID';
   		options.directDeleteMode = false;
   		options.limit = -1;
		options.orderBy = 'sortNo ASC';

   		options.onIndexChanging = Model.dataSysInfoIndexChanging;
   		options.onIndexChanged = Model.dataSysInfoIndexChanged;
   		options.onBeforeNew = null;
   		options.onAfterNew = Model.dataSysInfoAfterNew;
   		options.onBeforeDelete = null;
   		options.onAfterDelete = Model.dataSysInfoAfterDelete;
   		options.onValueChanged = Model.dataSysInfoValueChanged;
   		options.onDataChanged = Model.dataSysInfoDataChanged;
//      options.rowsWatcherFn = Model.rowsWatcherFn;
   		
   		$scope.dataSysInfo = new BizData(options);
//   	$scope.dataSysInfo.refreshData();
//   	$scope.dataSysInfo.deregIndex = $scope.$watch('dataSysInfo.currentIndex',$scope.dataSysInfo.watchCurrentIndex);
//   	$scope.dataSysInfo.deregID = $scope.$watch('dataSysInfo.currentID',$scope.dataSysInfo.watchCurrentID);
   		//监视对象中的所有变动
   		$scope.dataSysInfo.deregRows = $scope.$watch('dataSysInfo.rows',$scope.dataSysInfo.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
//      $scope.dataSysInfo.deregCollection = $scope.$watch('dataSysInfo.rows',$scope.dataSysInfo.watchCollection,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
   		//////////////////////////////////////////////
   		
	   		
   		//加载树形数据
   		Model.refresh();

   		

   		//单据配置参数设置
   		Model.setBillType = function() {
   			var treeData = $scope.dataSysInfo;
   			var rowID = treeData.getCurrentID();
   			var systemKind = treeData.getValue('systemKind',rowID);
   			var systemCode = treeData.getValue('systemCode',rowID);
   			var systemName = treeData.getValue('systemName',rowID);
   			if(systemKind=='app'){
   				var id = rowID;
   				var to = '/backcenter/billSetting/list';
   				var params = {
   						"id":id
   						,"systemCode":systemCode
   						,"systemName":systemName
   						,"recordState":"none"
   						,"appId": $scope.appId
   						,"appName": $scope.appName
   						};
   				var options = {};
   				$state.go(to,params,options);
   			}
   		};


   	    ///////////////////////////页面级////////////////////////////////////////
   		//返回
   		Model.goBack = function(event) {
   			window.history.go(-1);
   		}
   	    ///////////////////////////页面级////////////////////////////////////////
   	
   			
   	    return Model;

   	}
   
    
})